package com.imti.retrofitweatherdemo.fragment;

import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.imti.retrofitweatherdemo.NewsListAdapter;
import com.imti.retrofitweatherdemo.R;
import com.imti.retrofitweatherdemo.logic.NewsModelListItem;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class NewsListFragment extends LazyLoadFragment
{

    private SmartRefreshLayout mRefresh;

    private RecyclerView mNewsList;

    private List<NewsModelListItem> mNewsDataList = new ArrayList<>();

    private NewsListAdapter mNewsAdapter;

    @Override
    protected int setContentView()
    {
        return R.layout.fragment_news_list;
    }
    @Override
    protected void lazyLoad()
    {
        if (isInit)
        {
            initView();
        }
    }

    public void initView()
    {
        mRefresh = findViewById(R.id.news_list_refresh);
        mNewsList = findViewById(R.id.news_list);
        mNewsList.setLayoutManager(new LinearLayoutManager(getActivity()));

        mNewsAdapter = new NewsListAdapter(getActivity());

        //离线假数据构造
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

//        for (int i = 0; i < 20; i++)
//        {
//            NewsModelListItem model = new NewsModelListItem();
//
//            model.setBitmap(
//                BitmapFactory.decodeResource(getActivity().getResources(), R.mipmap.ic_launcher));
//
//            model.setTitle("测试新闻条目标题");
//            model.setDesc("测试新闻条目描述，只作为简单测试，并不作为实际显示内容，具体内容以接口请求回来的数据为准");
//
//            model.setTime(sdf.format(new Date()));
//
//            mNewsDataList.add(model);
//        }

        NewsDataModel.getInstance().dataReady().observe(requireActivity(),
            new Observer<List<NewsModelListItem>>()
            {
                @Override
                public void onChanged(List<NewsModelListItem> newsModelListItems)
                {
                    mNewsDataList.clear();
                    mNewsDataList.addAll(newsModelListItems);
                    mNewsAdapter.notifyDataSetChanged();
                    mNewsList.setVisibility(ViewGroup.VISIBLE);
                }
            });

        mNewsAdapter.setNewsModelLists(mNewsDataList);
        mNewsList.setAdapter(mNewsAdapter);
    }

    public void initData()
    {

    }

}